<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\GoodsCourse;

class GoodscourseController extends Base
{

	function index()
	{
		$keyword = input('post.keyword', '', 'serach_in');
		$goodsid = input('post.goodsid', '', 'serach_in');

		$query = GoodsCourse::where(['goods_id' => $goodsid]);
		if (!empty($keyword)) {
			$query->where('title', 'like', '%' . $keyword . '%');
		}

		$res = $query->order('sort asc,id desc')
			->paginate(getpage())
			->toArray();

		foreach ($res['data'] as &$vo) {
			$vo['image'] = toimg($vo['image']);
			$vo['source_type'] = getsourcetype($vo['source_type']);
		}

		$data['data'] = $res;
		return $this->json($data);
	}

	function listUpdate()
	{
		$data = only('id,status,sort');
		if (!$data['id']) throw new ValidateException('参数错误');
		GoodsCourse::update($data);

		return $this->json(['msg' => '操作成功']);
	}

	public function update()
	{
		$id = $this->request->post('id');
		$data = input('post.');
		unset($data['create_time']);

		if (empty($id)) {
			try {
				$res = GoodsCourse::create($data);
				if ($res->id && empty($data['sort'])) {
					GoodsCourse::update(['sort' => $res->id, 'id' => $res->id]);
				}
				$data['id'] = $res->id;
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}

			return $this->json(['msg' => '添加成功', 'data' => $res->id]);
		} else {

			try {
				GoodsCourse::update($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '修改成功']);
		}
	}

	function getInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		if ($id) {
			$data = GoodsCourse::field('*')->find($id)?->toArray();
		} else {
			$data = [
				'source_type' => 3,
				'sort' => 100,
				'status' => 1,
			];
		}

		return $this->json(['data' => $data]);
	}

	function delete()
	{
		return $this->del(new GoodsCourse());
	}

	function getField()
	{
		$data['source_typearray'] = getsourcetype();
		return $this->json(['data' => $data]);
	}
}
